<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Upload, InfoFilled } from '@element-plus/icons-vue'
import { analyzeImage as apiAnalyzeImage } from './services/api'

// 图像数据
const imageUrl = ref('')
const imageFile = ref(null)

// 提示文本
const promptText = ref('请详细描述这张图片中的内容，包括可见的物体、人物、场景和任何值得注意的细节。')

// 识别结果
const recognitionResult = ref(null)
const loading = ref(false)

// 格式化AI返回的结果
const formattedResult = computed(() => {
  if (!recognitionResult.value || !recognitionResult.value.data || !recognitionResult.value.data.result) return '';
  
  // 移除Markdown标记
  let text = recognitionResult.value.data.result;
  
  // 处理标题
  text = text.replace(/^#+\s+(.*?)$/gm, '<h3 class="result-title">$1</h3>');
  
  // 处理分隔线
  text = text.replace(/^---+$/gm, '<hr class="result-divider">');
  
  // 处理列表
  text = text.replace(/^(\d+)\.\s+(.*?)$/gm, '<div class="result-list-item"><span class="result-list-number">$1.</span> $2</div>');
  text = text.replace(/^-\s+(.*?)$/gm, '<div class="result-list-item"><span class="result-list-bullet">•</span> $1</div>');
  
  // 处理加粗
  text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 处理段落
  const paragraphs = text.split('\n\n');
  return paragraphs.map(p => {
    if (p.trim() === '') return '';
    if (p.startsWith('<h3') || p.startsWith('<div') || p.startsWith('<hr')) return p;
    return `<p class="result-paragraph">${p}</p>`;
  }).join('');
})

// 上传图像
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return
  }
  
  imageFile.value = file
  
  // 创建预览URL
  imageUrl.value = URL.createObjectURL(file)
}

// 发送图像到通义千问API进行识别
const analyzeImage = async () => {
  if (!imageFile.value) {
    ElMessage.warning('请先上传图像')
    return
  }
  
  loading.value = true
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '正在分析图像...'
  })
  
  try {
    // 调用API服务进行图像分析
    const result = await apiAnalyzeImage(imageFile.value, {
      prompt: promptText.value, // 用户输入的提示文本
      systemPrompt: "你是一个专业的图像分析助手，能够详细描述图像内容并提供深入分析。"
    })
    console.log(result);
    
    recognitionResult.value = result
    ElMessage.success('图像分析完成')
  } catch (error) {
    console.error('图像分析失败:', error)
    ElMessage.error(`分析失败: ${error.message || '未知错误'}`)
    recognitionResult.value = null
  } finally {
    loadingInstance.close()
    loading.value = false
  }
}

// 清除当前图像和结果
const clearAll = () => {
  imageUrl.value = ''
  imageFile.value = null
  recognitionResult.value = null
  
  // 清除文件输入框的值，允许重新上传相同的文件
  const fileInput = document.getElementById('image-upload')
  if (fileInput) fileInput.value = ''
}
</script>

<template>
  <div class="app-container">
    <header class="app-header">
      <div class="header-content">
        <h1>图像分析处理平台</h1>
      </div>
    </header>
    
    <main class="main-content">
      <!-- 左侧面板：图像上传区域 -->
      <div class="panel left-panel">
        <h2>图像上传</h2>
        
        <div class="upload-area" :class="{ 'has-image': imageUrl }">
          <div v-if="!imageUrl" class="upload-placeholder">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <p>点击或拖拽图片到此处上传</p>
            <input 
              type="file" 
              id="image-upload"
              accept="image/*" 
              @change="handleImageUpload" 
              class="file-input"
            />
          </div>
          
          <div v-else class="image-preview">
            <img :src="imageUrl" alt="预览图像" />
          </div>
        </div>
        
        <div class="prompt-input">
          <h3>提示文本</h3>
          <el-input
            v-model="promptText"
            type="textarea"
            :rows="3"
            placeholder="请输入提示文本，告诉AI你想了解图像的哪些方面..."
          />
        </div>
        
        <div class="action-buttons">
          <el-button 
            type="primary" 
            @click="analyzeImage" 
            :disabled="!imageUrl || loading"
            :loading="loading"
          >
            分析图像
          </el-button>
          
          <el-button @click="clearAll" :disabled="!imageUrl">
            清除
          </el-button>
        </div>
      </div>
      
      <!-- 右侧面板：识别结果区域 -->
      <div class="panel right-panel">
        <h2>识别结果</h2>
        
        <div v-if="!recognitionResult" class="no-result">
          <el-icon class="result-icon"><InfoFilled /></el-icon>
          <p>上传并分析图像后，识别结果将显示在这里</p>
        </div>
        
        <div v-else class="result-content">
          <el-tabs type="border-card">
            <el-tab-pane label="分析结果">
              <div class="result-item">
                <div class="ai-analysis-container">
                  <div class="ai-analysis" v-html="formattedResult"></div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="原始文本">
              <div class="result-item">
                <div class="ai-analysis">{{ recognitionResult.data.result }}</div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="原始响应">
              <pre class="json-view">{{ JSON.stringify(recognitionResult.data.rawResponse, null, 2) }}</pre>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </main>
    
    <footer class="app-footer">
      <p>© 2025 图像分析处理平台</p>
    </footer>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.app-header {
  background-color: #409eff;
  color: white;
  padding: 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
}

.header-logo {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: contain;
}

.main-content {
  display: flex;
  flex: 1;
  padding: 1rem;
  gap: 1rem;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
}

.panel {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.panel h2 {
  margin-top: 0;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 0.5rem;
  margin-bottom: 1rem;
}

.upload-area {
  flex: 1;
  border: 2px dashed #c0c4cc;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  min-height: 300px;
  margin-bottom: 1rem;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-area.has-image {
  border-style: solid;
}

.upload-placeholder {
  text-align: center;
  color: #909399;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.image-preview {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
}

.prompt-input {
  margin-bottom: 1rem;
}

.prompt-input h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.no-result {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.result-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.result-content {
  flex: 1;
}

.result-item {
  margin-bottom: 1.5rem;
}

.result-item h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #606266;
}

.ai-analysis-container {
  max-height: 500px;
  overflow: auto;
}

.ai-analysis {
  background-color: #f8f9fa;
  padding: 1rem;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  line-height: 1.6;
  font-size: 1rem;
  white-space: normal;
}

.ai-analysis .result-title {
  color: #303133;
  margin: 1.2rem 0 0.8rem;
  font-weight: 600;
  font-size: 1.2rem;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 0.5rem;
}

.ai-analysis .result-title:first-child {
  margin-top: 0;
}

.ai-analysis .result-paragraph {
  margin: 0.8rem 0;
  text-align: justify;
}

.ai-analysis .result-divider {
  border: 0;
  border-top: 1px solid #ebeef5;
  margin: 1rem 0;
}

.ai-analysis .result-list-item {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
  position: relative;
}

.ai-analysis .result-list-number,
.ai-analysis .result-list-bullet {
  position: absolute;
  left: 0;
  color: #409eff;
  font-weight: bold;
}

.ai-analysis strong {
  color: #303133;
  font-weight: 600;
}

.json-view {
  background-color: #f5f7fa;
  padding: 1rem;
  border-radius: 4px;
  overflow: auto;
  max-height: 400px;
  font-family: monospace;
  white-space: pre-wrap;
}

.app-footer {
  background-color: #303133;
  color: #909399;
  text-align: center;
  padding: 1rem;
  margin-top: auto;
}
</style>